package cn.iocoder.yudao.framework.validation;

import cn.hutool.core.util.StrUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @author 山野羡民
 * @since 2025/01/18
 */
public class ChineseValidator implements ConstraintValidator<Chinese, String> {
    private boolean contains;

    @Override
    public void initialize(Chinese constraintAnnotation) {
        this.contains = constraintAnnotation.contains();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果输入为空，默认不校验，即校验通过
        if (StrUtil.isBlank(value)) {
            return true;
        }
        // 校验含汉字
        if (contains) {
            return cn.hutool.core.lang.Validator.hasChinese(value);
        }
        // 校验是汉字
        return cn.hutool.core.lang.Validator.isChinese(value);
    }

}
